import { defineStore } from "pinia"
import { AuthState } from "@/stores/interface"
import { getPermsApi } from "@/api/modules/login"
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList } from "@/utils"
import { LoginSpace } from "@/api/interface/login"
// 初始化动态路由
function formatMenu(arrlist: LoginSpace.UserMenu[]) {
  let objarr: Menu.MenuOptions[] = []
  arrlist.forEach((e: LoginSpace.UserMenu) => {
    if (e?.children && e.children.length !== 0) {
      objarr.push({
        path: e.path || "",
        name: e.path ? e.path.split("/")[e.path.split("/").length - 1] : "",
        redirect: e.component ? e.component.split("views")[1] : undefined,
        meta: {
          icon: e.icon,
          title: e.name,
          isLink: e.isLink,
          isHide: e.isHide,
          isFull: e.isFull,
          isAffix: e.isAffix,
          isKeepAlive: e.isKeepAlive
        },
        children: e.children.length === 0 ? [] : formatMenu(e.children)
      })
    } else {
      objarr.push({
        path: e.path || "",
        name: e.path ? e.path.split("/")[e.path.split("/").length - 1] : "",
        component: e.component ? e.component.split("views")[1] : undefined,
        meta: {
          icon: e.icon,
          title: e.name,
          isLink: e.isLink,
          isHide: e.isHide,
          isFull: e.isFull,
          isAffix: e.isAffix,
          isKeepAlive: e.isKeepAlive
        }
      })
    }
  })
  return objarr
}

export const useAuthStore = defineStore({
  id: "AuthStore",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: [],
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: ""
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
  },
  actions: {
    // 获取 按钮权限
    async getAuthButtonList() {
      const { data } = await getPermsApi()
      console.log(data)
      this.authButtonList = data.perms
    },
    // 获取 菜单权限
    async getAuthMenuList() {
      const { data } = await getPermsApi()
      this.authMenuList = formatMenu(data.menus)
    },
    // 设置 路由名称
    async setRouteName(name: string) {
      this.routeName = name
    }
  }
})
